{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {
    "origin_pos": 0
   },
   "source": [
    "# 文本预处理\n",
    ":label:`sec_text_preprocessing`\n",
    "\n",
    "我们回顾和评估了序列数据的统计工具和预测挑战。这些数据可以有多种形式。具体来说，正如我们将在本书的许多章节中重点介绍的那样，文本是序列数据最常见例子。例如，一篇文章可以简单地看作是一个单词序列，甚至是一个字符序列。为了方便我们将来对序列数据的实验，我们将在本节中专门解释文本的常见预处理步骤。通常，这些步骤包括：\n",
    "\n",
    "1. 将文本作为字符串加载到内存中。\n",
    "1. 将字符串拆分为标记（如，单词和字符）。\n",
    "1. 建立一个词汇表，将拆分的标记映射到数字索引。\n",
    "1. 将文本转换为数字索引序列，以便模型可以轻松地对其进行操作。\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "origin_pos": 2,
    "tab": [
     "pytorch"
    ]
   },
   "outputs": [],
   "source": [
    "import collections\n",
    "import re\n",
    "from d2l import torch as d2l"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "origin_pos": 4
   },
   "source": [
    "## 读取数据集\n",
    "\n",
    "为了开始，我们从H.G.Well的[*时光机器*](http://www.gutenberg.org/ebooks/35)中加载文本。这是一个相当小的语料库，只有30000多个单词，但对于我们想要说明的目标来说，这足够了。现实中的文档集合可能会包含数十亿个单词。下面的函数将数据集读取到文本行组成的列表中，其中每行都是一个字符串。为简单起见，这里我们忽略标点符号和大写。\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "origin_pos": 5,
    "tab": [
     "pytorch"
    ]
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "# text lines: 3221\n",
      "the time machine by h g wells\n",
      "twinkled and his usually pale face was flushed and animated the\n"
     ]
    }
   ],
   "source": [
    "#@save\n",
    "d2l.DATA_HUB['time_machine'] = (d2l.DATA_URL + 'timemachine.txt',\n",
    "                                '090b5e7e70c295757f55df93cb0a180b9691891a')\n",
    "\n",
    "def read_time_machine():  #@save\n",
    "    \"\"\"Load the time machine dataset into a list of text lines.\"\"\"\n",
    "    with open(d2l.download('time_machine'), 'r') as f:\n",
    "        lines = f.readlines()\n",
    "    return [re.sub('[^A-Za-z]+', ' ', line).strip().lower() for line in lines]\n",
    "\n",
    "lines = read_time_machine()\n",
    "print(f'# text lines: {len(lines)}')\n",
    "print(lines[0])\n",
    "print(lines[10])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "origin_pos": 6
   },
   "source": [
    "## 标记化\n",
    "\n",
    "以下 `tokenize` 函数将列表作为输入，列表中的每个元素是文本序列（如，文本行）。每个文本序列被拆分成一个标记列表。*标记*（token）是文本的基本单位。最后返回一个标记列表，其中每个标记都是一个字符串（string）。\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {
    "origin_pos": 7,
    "tab": [
     "pytorch"
    ]
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "['the', 'time', 'machine', 'by', 'h', 'g', 'wells']\n",
      "[]\n",
      "[]\n",
      "[]\n",
      "[]\n",
      "['i']\n",
      "[]\n",
      "[]\n",
      "['the', 'time', 'traveller', 'for', 'so', 'it', 'will', 'be', 'convenient', 'to', 'speak', 'of', 'him']\n",
      "['was', 'expounding', 'a', 'recondite', 'matter', 'to', 'us', 'his', 'grey', 'eyes', 'shone', 'and']\n",
      "['twinkled', 'and', 'his', 'usually', 'pale', 'face', 'was', 'flushed', 'and', 'animated', 'the']\n"
     ]
    }
   ],
   "source": [
    "def tokenize(lines, token='word'):  #@save\n",
    "    \"\"\"将文本行拆分为单词或字符标记。\"\"\"\n",
    "    if token == 'word':\n",
    "        return [line.split() for line in lines]\n",
    "    elif token == 'char':\n",
    "        return [list(line) for line in lines]\n",
    "    else:\n",
    "        print('错误：未知令牌类型：' + token)\n",
    "\n",
    "tokens = tokenize(lines)\n",
    "for i in range(11):\n",
    "    print(tokens[i])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "origin_pos": 8
   },
   "source": [
    "## 词汇\n",
    "\n",
    "标记的字符串类型不方便模型使用，因为模型需要输入数字。现在，让我们构建一个字典，通常也叫做*词表*（Vocabulary）来将字符串标记映射到从0开始的数字索引中。为此，我们首先统计训练集中所有文档中的唯一标记，即*语料*（corpus），然后根据每个唯一标记的出现频率为其分配一个数字索引。很少出现的标记通常被移除，这可以降低复杂性。语料库中不存在或已删除的任何标记都将映射到一个特殊的未知标记 “&lt;unk&gt;” 。我们可以选择添加保留令牌的列表，例如“&lt;pad&gt;”表示填充；“&lt;bos&gt;”表示序列的开始；“&lt;eos&gt;”表示序列的结束。\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {
    "origin_pos": 9,
    "tab": [
     "pytorch"
    ]
   },
   "outputs": [],
   "source": [
    "class Vocab:  #@save\n",
    "    \"\"\"文本词表\"\"\"\n",
    "    def __init__(self, tokens=None, min_freq=0, reserved_tokens=None):\n",
    "        if tokens is None:\n",
    "            tokens = []\n",
    "        if reserved_tokens is None:\n",
    "            reserved_tokens = []\n",
    "        # 按出现频率排序\n",
    "        counter = count_corpus(tokens)\n",
    "        self.token_freqs = sorted(counter.items(), key=lambda x: x[1],\n",
    "                                  reverse=True)\n",
    "        # 未知标记的索引为0\n",
    "        self.unk, uniq_tokens = 0, ['<unk>'] + reserved_tokens\n",
    "        uniq_tokens += [\n",
    "            token for token, freq in self.token_freqs\n",
    "            if freq >= min_freq and token not in uniq_tokens]\n",
    "        self.idx_to_token, self.token_to_idx = [], dict()\n",
    "        for token in uniq_tokens:\n",
    "            self.idx_to_token.append(token)\n",
    "            self.token_to_idx[token] = len(self.idx_to_token) - 1\n",
    "\n",
    "    def __len__(self):\n",
    "        return len(self.idx_to_token)\n",
    "\n",
    "    def __getitem__(self, tokens):\n",
    "        if not isinstance(tokens, (list, tuple)):\n",
    "            return self.token_to_idx.get(tokens, self.unk)\n",
    "        return [self.__getitem__(token) for token in tokens]\n",
    "\n",
    "    def to_tokens(self, indices):\n",
    "        if not isinstance(indices, (list, tuple)):\n",
    "            return self.idx_to_token[indices]\n",
    "        return [self.idx_to_token[index] for index in indices]\n",
    "\n",
    "def count_corpus(tokens):  #@save\n",
    "    \"\"\"Count token frequencies.\"\"\"\n",
    "    # 这里的 `tokens` 是1D列表或2D列表\n",
    "    if len(tokens) == 0 or isinstance(tokens[0], list):\n",
    "        # 将令牌列表展平\n",
    "        tokens = [token for line in tokens for token in line]\n",
    "    return collections.Counter(tokens)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "origin_pos": 10
   },
   "source": [
    "我们使用时光机器数据集作为语料库来构建词汇表。然后，我们打印前几个常见标记及其索引。\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {
    "origin_pos": 11,
    "tab": [
     "pytorch"
    ]
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[('<unk>', 0), ('the', 1), ('i', 2), ('and', 3), ('of', 4), ('a', 5), ('to', 6), ('was', 7), ('in', 8), ('that', 9)]\n"
     ]
    }
   ],
   "source": [
    "vocab = Vocab(tokens)\n",
    "print(list(vocab.token_to_idx.items())[:10])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "origin_pos": 12
   },
   "source": [
    "现在我们可以将每一行文本转换成一个数字索引列表。\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {
    "origin_pos": 13,
    "tab": [
     "pytorch"
    ]
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "words: ['the', 'time', 'machine', 'by', 'h', 'g', 'wells']\n",
      "indices: [1, 19, 50, 40, 2183, 2184, 400]\n",
      "words: ['twinkled', 'and', 'his', 'usually', 'pale', 'face', 'was', 'flushed', 'and', 'animated', 'the']\n",
      "indices: [2186, 3, 25, 1044, 362, 113, 7, 1421, 3, 1045, 1]\n"
     ]
    }
   ],
   "source": [
    "for i in [0, 10]:\n",
    "    print('words:', tokens[i])\n",
    "    print('indices:', vocab[tokens[i]])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "origin_pos": 14
   },
   "source": [
    "## 把所有的东西放在一起\n",
    "\n",
    "使用上述函数，我们将所有内容打包到 `load_corpus_time_machine` 函数中，该函数返回 `corpus`（标记索引列表）和 `vocab`（时光机器语料库的词汇表）。我们在这里所做的修改是：\n",
    "- 1、我们将文本 标记化为字符，而不是单词，以简化后面部分中的训练；\n",
    "- 2、`corpus`是单个列表，而不是标记列表嵌套，因为时光机器数据集中的每个文本行不一定是句子或段落。\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {
    "origin_pos": 15,
    "tab": [
     "pytorch"
    ]
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(170580, 28)"
      ]
     },
     "execution_count": 7,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "def load_corpus_time_machine(max_tokens=-1):  #@save\n",
    "    \"\"\"返回时光机器数据集的令牌索引和词汇表。\"\"\"\n",
    "    lines = read_time_machine()\n",
    "    tokens = tokenize(lines, 'char')\n",
    "    vocab = Vocab(tokens)\n",
    "    # 因为时光机器数据集中的每一个文本行不一定是一个句子或段落，\n",
    "    # 所以将所有文本行展平到一个列表中\n",
    "    corpus = [vocab[token] for line in tokens for token in line]\n",
    "    if max_tokens > 0:\n",
    "        corpus = corpus[:max_tokens]\n",
    "    return corpus, vocab\n",
    "\n",
    "corpus, vocab = load_corpus_time_machine()\n",
    "len(corpus), len(vocab)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "origin_pos": 16
   },
   "source": [
    "## 小结\n",
    "\n",
    "* 文本是序列数据的一种重要形式。\n",
    "* 为了对文本进行预处理，我们通常将文本拆分为标记，构建词汇表将标记字符串映射为数字索引，并将文本数据转换为标记索引以供模型操作。\n",
    "\n",
    "## 练习\n",
    "\n",
    "1. 标记化是一个关键的预处理步骤。它因语言而异。尝试找到另外三种常用的文本标记方法。\n",
    "1. 在本节的实验中，将文本标记为单词，并更改 `Vocab` 实例的 `min_freq` 参数。这对词汇量有何影响？\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "origin_pos": 18,
    "tab": [
     "pytorch"
    ]
   },
   "source": [
    "[Discussions](https://discuss.d2l.ai/t/2094)\n"
   ]
  }
 ],
 "metadata": {
  "language_info": {
   "name": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}